Popular Searches
Popular Course Categories
Popular Courses

Creating BEFORE INSERT and AFTER INSERT Triggers

Creating BEFORE INSERT and AFTER INSERT Triggers

Triggers, Events, and Cursors

Creating BEFORE INSERT and AFTER INSERT Triggers in MySQL

Course: MySQL Training

Topic: Creating BEFORE INSERT and AFTER INSERT Triggers

Course Link: MySQL Training Course

Demo Link: Register for a Free Course Demo

Official Reference: MySQL Trigger Syntax and Examples


1. Introduction to MySQL Triggers

A trigger in MySQL is a database object associated with a table that automatically executes when a specified table operation occurs. Triggers are commonly used to validate data, modify values before insertion, record activity, and maintain audit logs.

MySQL supports triggers for INSERT, UPDATE, and DELETE operations. For INSERT operations, the two main trigger types are BEFORE INSERT and AFTER INSERT.

  • BEFORE INSERT: Executes before a new row is inserted into a table. It can validate or modify the incoming values.
  • AFTER INSERT: Executes after a new row has been successfully inserted. It can record the insertion or perform related database operations.

For example, an online shopping database might use a BEFORE INSERT trigger to standardize a product name and an AFTER INSERT trigger to record the newly created product in an audit table.

2. Learning Objectives

After completing this topic, you will be able to:

  • Understand the meaning and purpose of MySQL triggers.
  • Differentiate BEFORE INSERT and AFTER INSERT triggers.
  • Understand the NEW keyword and access incoming column values.
  • Create triggers using CREATE TRIGGER.
  • Modify incoming data before insertion.
  • Record newly inserted rows in an audit table.
  • Use DELIMITER and BEGIN...END for multiple SQL statements.
  • Inspect, test, troubleshoot, and remove triggers.
  • Apply triggers to practical database scenarios.

3. What Is a Trigger in MySQL?

A trigger is a stored database program that runs automatically when its associated table experiences a specified event. Unlike a stored procedure, which is normally executed by calling it explicitly, a trigger is activated by the relevant table operation.

3.1 Key Characteristics

  • A trigger belongs to a particular table.
  • It runs automatically when its triggering event occurs.
  • It can execute once for each affected row.
  • It can contain a single SQL statement or a compound statement.
  • It can access values from the row being inserted through the NEW keyword.
  • Its behavior depends on the trigger timing and event.

3.2 Common Uses of Triggers

Use Case Purpose Example
Data validation Check incoming values before insertion. Reject a negative product price.
Data standardization Adjust values to a consistent format. Convert a name to uppercase.
Audit logging Record newly inserted data. Save new employee details in an audit table.
Activity tracking Track when a row is created. Record a product creation timestamp.
Related table maintenance Perform a related database operation. Update a summary table after a successful insert.

4. Understanding BEFORE INSERT Triggers

A BEFORE INSERT trigger executes before MySQL inserts a new row into the associated table. It is especially useful when incoming data needs to be checked, transformed, or assigned a calculated value before storage.

4.1 How a BEFORE INSERT Trigger Works

  1. An application or user submits an INSERT statement.
  2. MySQL prepares the values for the new row.
  3. The BEFORE INSERT trigger executes for the row operation.
  4. The trigger can inspect the incoming values using NEW.column_name.
  5. Where permitted, the trigger can modify incoming values using SET NEW.column_name.
  6. MySQL attempts to insert the resulting row.
  7. If the trigger or insertion fails, the row operation does not complete successfully.

4.2 Basic Syntax

CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
trigger_body;
Keyword Explanation
CREATE TRIGGER Creates a new trigger.
trigger_name The unique name of the trigger within its schema.
BEFORE INSERT Specifies that the trigger runs before an insert operation.
ON table_name Identifies the table associated with the trigger.
FOR EACH ROW Runs the trigger body for each row affected by the operation.
trigger_body Contains the SQL statement or statements to execute.

5. Understanding AFTER INSERT Triggers

An AFTER INSERT trigger executes after a row has been successfully inserted into the associated table. It is useful for recording insert activity, maintaining audit information, and performing related database operations.

5.1 How an AFTER INSERT Trigger Works

  1. An INSERT statement requests a new row.
  2. Any applicable BEFORE INSERT trigger executes first.
  3. MySQL performs the row insertion.
  4. If the insertion and applicable BEFORE triggers succeed, the AFTER INSERT trigger executes.
  5. The AFTER INSERT trigger can read the inserted row's values through NEW.column_name.
  6. The trigger can perform permitted follow-up operations, such as inserting an audit record into another table.

5.2 Basic Syntax

CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
trigger_body;

Unlike a BEFORE INSERT trigger, an AFTER INSERT trigger cannot change the values of the row that has already been inserted by assigning to NEW.column_name. If a value needs to be adjusted before storage, use a BEFORE INSERT trigger instead.

6. Difference Between BEFORE INSERT and AFTER INSERT

Feature BEFORE INSERT AFTER INSERT
Execution time Before row insertion. After successful row insertion.
Primary purpose Validate or prepare incoming data. Record or respond to a completed insertion.
Read NEW values Yes. Yes.
Modify the incoming row using SET NEW Yes, where permitted. No.
Insert into an audit table Possible, but it records an attempted operation rather than necessarily a completed insertion. Suitable for recording a successful insertion.
Execution condition Activated by the attempt to insert a row, even if the attempt later fails. Runs only if the applicable BEFORE trigger and row operation succeed.
Typical example Normalize a product name. Record the new product in an audit table.

7. Understanding the NEW Keyword

In an INSERT trigger, NEW refers to the values of the row being inserted. It allows the trigger to inspect individual column values and, in a BEFORE INSERT trigger, modify them where permitted.

7.1 Example

NEW.product_name
NEW.price
NEW.category

Suppose a product table receives the following values:

INSERT INTO products (product_name, price, category)
VALUES ('wireless mouse', 799.00, 'accessories');

Inside the trigger, the incoming values can be accessed as follows:

  • NEW.product_name contains wireless mouse.
  • NEW.price contains 799.00.
  • NEW.category contains accessories.

In a BEFORE INSERT trigger, a permitted assignment such as SET NEW.product_name = UPPER(NEW.product_name); can change the value before storage.

7.2 NEW and OLD Comparison

Keyword Meaning Availability
NEW Represents the new row values. INSERT and UPDATE triggers.
OLD Represents the existing row values before a change. UPDATE and DELETE triggers.

For INSERT triggers, use NEW because there is no previous row associated with the insertion.

8. Preparing the Database for Examples

In the following examples, a products table will be used to demonstrate both trigger types. Run the table creation statement before creating the triggers.

8.1 Create a Database

CREATE DATABASE mysql_trigger_demo;
USE mysql_trigger_demo;

If you already have a suitable database, you can select it with USE instead of creating another one.

8.2 Create the Products Table

CREATE TABLE products (
    product_id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    category VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Explanation of the columns:

  • product_id uniquely identifies each product and is generated automatically.
  • product_name stores the product's name.
  • price stores the product's price.
  • category stores the product category.
  • created_at records the creation timestamp using a default value.

9. Creating a BEFORE INSERT Trigger to Standardize Product Names

Suppose users enter product names in different formats, such as wireless mouse, Wireless Mouse, or WIRELESS MOUSE. A BEFORE INSERT trigger can convert incoming product names to uppercase before they are stored.

9.1 Create the Trigger

DELIMITER //

CREATE TRIGGER before_product_insert
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
    SET NEW.product_name = UPPER(NEW.product_name);
END//

DELIMITER ;

9.2 Explanation

  • DELIMITER // temporarily changes the statement delimiter in the MySQL command-line client.
  • CREATE TRIGGER before_product_insert defines the trigger name.
  • BEFORE INSERT ON products associates the trigger with insert operations on the products table.
  • FOR EACH ROW runs the trigger for each affected row.
  • UPPER() converts the product name to uppercase.
  • SET NEW.product_name assigns the converted value to the incoming row.
  • DELIMITER ; restores the usual delimiter in the command-line client.

9.3 Test the Trigger

INSERT INTO products (product_name, price, category)
VALUES ('wireless mouse', 799.00, 'Accessories');

SELECT product_id, product_name, price, category
FROM products;

Expected product-name result:

product_name
------------
WIRELESS MOUSE

The original INSERT statement supplied a lowercase product name, but the trigger changed the incoming value before MySQL stored the row.

10. Creating a BEFORE INSERT Trigger for Price Validation

A BEFORE INSERT trigger can validate incoming prices. For example, a business may require all product prices to be greater than zero.

10.1 Create a Trigger Using SIGNAL

DELIMITER //

CREATE TRIGGER before_product_price_check
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
    IF NEW.price <= 0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Product price must be greater than zero';
    END IF;
END//

DELIMITER ;

10.2 Explanation

  • The IF statement checks the incoming price.
  • If the price is zero or negative, the trigger raises an error.
  • SIGNAL SQLSTATE '45000' raises a user-defined exception.
  • MESSAGE_TEXT provides an understandable error message.
  • If the condition is false, the trigger allows the operation to continue, subject to other constraints and rules.

10.3 Test with a Valid Price

INSERT INTO products (product_name, price, category)
VALUES ('Mechanical Keyboard', 2499.00, 'Accessories');

The trigger allows the insertion because the price is greater than zero.

10.4 Test with an Invalid Price

INSERT INTO products (product_name, price, category)
VALUES ('Broken Price Example', -100.00, 'Accessories');

Expected behavior: MySQL reports the custom error, and the row is not inserted successfully.

Important: A table-level CHECK constraint may also be appropriate for straightforward rules such as CHECK (price > 0). Use triggers when the requirement needs procedural logic or related actions beyond a simple constraint.

11. Creating an Audit Table for AFTER INSERT

An audit table stores information about actions performed on a database. In this example, each successfully inserted product will generate a corresponding audit record.

11.1 Create the Audit Table

CREATE TABLE product_audit (
    audit_id INT AUTO_INCREMENT PRIMARY KEY,
    product_id INT NOT NULL,
    product_name VARCHAR(100) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    action_type VARCHAR(20) NOT NULL,
    action_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

The audit table stores the product identifier, product name, price, action type, and timestamp associated with the recorded event.

12. Creating an AFTER INSERT Trigger

Now create a trigger that records product information in product_audit after a product has been inserted successfully.

12.1 Create the Trigger

DELIMITER //

CREATE TRIGGER after_product_insert
AFTER INSERT ON products
FOR EACH ROW
BEGIN
    INSERT INTO product_audit (
        product_id,
        product_name,
        price,
        action_type
    )
    VALUES (
        NEW.product_id,
        NEW.product_name,
        NEW.price,
        'INSERT'
    );
END//

DELIMITER ;

12.2 Explanation

  • CREATE TRIGGER after_product_insert defines the trigger.
  • AFTER INSERT ON products runs it after a successful row insertion into products.
  • NEW.product_id accesses the identifier of the inserted product.
  • NEW.product_name accesses the inserted product name.
  • NEW.price accesses the inserted price.
  • The INSERT statement adds a corresponding row to product_audit.
  • 'INSERT' identifies the type of recorded action.

12.3 Test the AFTER INSERT Trigger

INSERT INTO products (product_name, price, category)
VALUES ('USB-C Hub', 1499.00, 'Accessories');

SELECT * FROM product_audit;

Expected audit information includes the new product's identifier, name, price, action type, and action timestamp. The exact generated identifiers and timestamps depend on the database state and execution time.

The AFTER INSERT trigger does not need to be called manually. It executes automatically when the associated insertion succeeds.

13. Using BEFORE INSERT and AFTER INSERT Together

A common design uses both trigger types on the same table. The BEFORE INSERT trigger prepares or validates incoming values, while the AFTER INSERT trigger records the final inserted values.

13.1 Execution Flow

  1. A user inserts a product named usb-c hub.
  2. The BEFORE INSERT trigger converts the name to USB-C HUB.
  3. The price validation trigger checks that the price is greater than zero.
  4. MySQL inserts the product if the checks and other database requirements succeed.
  5. The AFTER INSERT trigger copies the inserted product information into product_audit.
  6. The application can query products and product_audit to verify the results.

13.2 Combined Test

INSERT INTO products (product_name, price, category)
VALUES ('usb-c hub', 1499.00, 'Accessories');

SELECT product_id, product_name, price
FROM products
ORDER BY product_id DESC;

SELECT product_id, product_name, price, action_type, action_time
FROM product_audit
ORDER BY audit_id DESC;

For the newly inserted product, the products table should contain the standardized name, and the audit table should contain the corresponding inserted values.

Note: Multiple triggers can exist for the same table, event, and timing. If execution order matters, MySQL supports the FOLLOWS and PRECEDES clauses for triggers with the same timing and event. Otherwise, triggers created for the same timing and event execute in creation order.

14. Understanding DELIMITER and BEGIN...END

When creating a trigger containing multiple SQL statements in the MySQL command-line client, the delimiter must be changed temporarily. This prevents the client from treating a semicolon inside the trigger body as the end of the entire CREATE TRIGGER statement.

14.1 Example

DELIMITER //

CREATE TRIGGER example_before_insert
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
    SET NEW.product_name = TRIM(NEW.product_name);
    SET NEW.product_name = UPPER(NEW.product_name);
END//

DELIMITER ;

In this example, BEGIN and END group two statements into a compound trigger body. The alternate delimiter is used by the client while defining the trigger; it is not part of the trigger's stored business logic.

Some graphical database tools manage statement execution and delimiters differently. Follow the tool's SQL editor instructions if it reports a delimiter-related error.

15. Viewing and Managing Triggers

15.1 Show All Triggers

SHOW TRIGGERS;

This command displays trigger information for the currently selected database.

15.2 Show Triggers for a Specific Database

SHOW TRIGGERS FROM mysql_trigger_demo;

15.3 Inspect a Trigger Definition

SHOW CREATE TRIGGER before_product_insert;

This statement displays the stored definition of the specified trigger. Use the correct trigger name and schema when necessary.

15.4 Remove a Trigger

DROP TRIGGER IF EXISTS after_product_insert;

DROP TRIGGER removes the trigger definition. It does not remove the products table or automatically delete audit records already created by earlier trigger executions.

16. Multiple-Row INSERT Operations

MySQL triggers operate on a per-row basis. When a single INSERT statement inserts several rows, the applicable row trigger executes for each row being processed.

16.1 Example

INSERT INTO products (product_name, price, category)
VALUES
    ('laptop stand', 899.00, 'Accessories'),
    ('webcam', 1599.00, 'Electronics'),
    ('desk lamp', 699.00, 'Home');

If the inserts succeed, the BEFORE INSERT trigger processes each incoming row, and the AFTER INSERT trigger creates an audit record for each successfully inserted row.

16.2 Verify the Results

SELECT product_id, product_name, price, category
FROM products
ORDER BY product_id;

SELECT audit_id, product_id, product_name, action_type
FROM product_audit
ORDER BY audit_id;

Verify that each newly inserted product has the expected standardized name and a corresponding audit record.

17. Error Handling and Transaction Behavior

Trigger errors can cause the statement that activated the trigger to fail. For transactional tables such as InnoDB, changes made by a failed statement are rolled back as part of statement failure. Nontransactional tables may not be able to roll back earlier changes in the same way.

17.1 Common Error Scenarios

  • A BEFORE INSERT trigger raises an error because the incoming price is invalid.
  • A required column is missing or contains a value that violates a constraint.
  • An AFTER INSERT trigger fails while inserting an audit record.
  • The trigger references a nonexistent column or table.
  • The database account lacks a required privilege.

17.2 Why an AFTER INSERT Trigger Can Fail

Suppose the AFTER INSERT trigger tries to insert a value into a required audit-table column but does not provide that value. If the audit insertion fails, the statement that triggered it also fails. With transactional tables, the related statement changes are rolled back.

For this reason, trigger bodies should be tested carefully, and related tables should have compatible data types, constraints, and expected values.

18. Important Rules and Limitations

  • Use NEW to access incoming row values in INSERT triggers.
  • Use SET NEW.column_name only in a BEFORE trigger when modifying an incoming value is permitted.
  • Do not try to change the inserted row through NEW assignments in an AFTER INSERT trigger.
  • BEFORE triggers can execute even when the attempted insertion ultimately fails.
  • AFTER INSERT triggers execute only when the relevant row operation and applicable BEFORE triggers succeed.
  • Trigger errors can cause the statement that activated the trigger to fail.
  • MySQL triggers are row-level triggers and use FOR EACH ROW.
  • Use meaningful names such as before_product_insert and after_product_insert.
  • Triggers cannot directly use transaction-control statements such as COMMIT or ROLLBACK.
  • Avoid unnecessary work inside triggers because every affected row can execute the trigger body.
  • Review trigger interactions when using INSERT ... ON DUPLICATE KEY UPDATE because duplicate-key handling can activate insert and update triggers depending on the operation performed.

19. Best Practices for MySQL Triggers

19.1 Keep Trigger Logic Simple

Use triggers for focused operations such as normalization, validation, and audit recording. Avoid placing large amounts of business logic inside a trigger when a service layer or stored procedure would be easier to test and maintain.

19.2 Prefer Constraints for Simple Rules

Use NOT NULL, UNIQUE, FOREIGN KEY, and CHECK constraints where appropriate. Constraints express database rules directly and are often clearer than procedural validation triggers.

19.3 Avoid Recursive or Unexpected Side Effects

Understand which tables a trigger modifies and whether those changes could interact with other triggers. Keep related operations predictable and document their behavior.

19.4 Use Transactional Tables

For audit records that must remain consistent with inserted data, use transactional storage engines such as InnoDB for the relevant tables. Test how failures affect the full statement.

19.5 Test Both Valid and Invalid Inputs

Check normal values, empty strings, NULL values, boundary values, duplicate keys, and multi-row insertions. Confirm that the trigger behaves as intended for each case.

19.6 Document Trigger Dependencies

Record the trigger's purpose, the table it affects, the conditions it checks, and the related tables it modifies. This helps developers understand database behavior when troubleshooting applications.

20. Common Mistakes and Troubleshooting

Problem Possible Cause Solution
Trigger creation fails near END The client interprets an internal semicolon as the end of the statement. Use DELIMITER when required by the MySQL client.
Trigger does not appear to run The trigger is attached to another table or database. Check SHOW TRIGGERS and verify the selected schema.
NEW.column_name is invalid The column name is misspelled or does not exist. Check the table definition with DESCRIBE table_name.
Cannot modify NEW in an AFTER trigger The row has already been inserted. Move the transformation to a BEFORE INSERT trigger.
Audit row is missing The insert failed, the trigger was not created correctly, or the audit insertion failed. Inspect the trigger definition and the SQL error message.
Insert fails with a custom message A SIGNAL condition was satisfied. Check the incoming values and the validation rules.
Duplicate trigger name error A trigger with the same name already exists in the schema. Choose a different name or intentionally drop the existing trigger before recreating it.
Unexpected results with multiple triggers Trigger execution order or side effects are not understood. Inspect all triggers for the same table, event, and timing; define ordering where necessary.

21. Practical Mini Project: Product Registration and Audit Logging

Project Objective: Build a small product registration database that standardizes product names, rejects invalid prices, and records successfully inserted products in an audit table.

21.1 Project Requirements

  • Create a products table.
  • Create a product_audit table.
  • Create a BEFORE INSERT trigger to standardize product names.
  • Create a BEFORE INSERT trigger to reject prices less than or equal to zero.
  • Create an AFTER INSERT trigger to record successfully inserted products.
  • Test valid and invalid values.
  • Verify the final products and audit records.

21.2 Insert Sample Products

INSERT INTO products (product_name, price, category)
VALUES
    ('wireless mouse', 799.00, 'Accessories'),
    ('gaming keyboard', 2499.00, 'Accessories'),
    ('portable speaker', 1899.00, 'Electronics');

21.3 Verify Product Records

SELECT product_id, product_name, price, category, created_at
FROM products
ORDER BY product_id;

21.4 Verify Audit Records

SELECT audit_id, product_id, product_name, price, action_type, action_time
FROM product_audit
ORDER BY audit_id;

21.5 Test an Invalid Product

INSERT INTO products (product_name, price, category)
VALUES ('invalid product', 0, 'Testing');

The price-validation trigger should reject this insertion. Confirm that the invalid product does not appear as a successfully inserted row and that no successful-insert audit record was created for it.

21.6 Expected Learning Outcome

By completing this project, you will understand how BEFORE INSERT triggers prepare and validate incoming data, how AFTER INSERT triggers respond to successful insertions, and how audit records can help monitor database activity.

22. Practice Exercises

  1. Create a BEFORE INSERT trigger that removes leading and trailing spaces from a product name using TRIM().
  2. Create a BEFORE INSERT trigger that converts product categories to uppercase.
  3. Create a BEFORE INSERT trigger that rejects a NULL product name with a custom error.
  4. Create an AFTER INSERT trigger that stores the product ID and category in a separate product-category log table.
  5. Insert three products in one statement and verify that three audit records are generated.
  6. Use SHOW TRIGGERS to list the triggers in your database.
  7. Use SHOW CREATE TRIGGER to inspect one trigger's SQL definition.
  8. Drop a test trigger using DROP TRIGGER IF EXISTS.

23. Practice Exercise Solutions

23.1 Remove Extra Spaces from a Product Name

DELIMITER //

CREATE TRIGGER before_product_trim
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
    SET NEW.product_name = TRIM(NEW.product_name);
END//

DELIMITER ;

23.2 Convert Categories to Uppercase

DELIMITER //

CREATE TRIGGER before_product_category_upper
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
    IF NEW.category IS NOT NULL THEN
        SET NEW.category = UPPER(NEW.category);
    END IF;
END//

DELIMITER ;

These are additional practice examples. If you already have another BEFORE INSERT trigger for the same table, event, and timing, MySQL permits multiple triggers, but you should manage their execution order and avoid redundant transformations.

23.3 Reject a NULL Product Name

DELIMITER //

CREATE TRIGGER before_product_name_check
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
    IF NEW.product_name IS NULL THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Product name cannot be NULL';
    END IF;
END//

DELIMITER ;

The table's NOT NULL constraint also protects the column. This example demonstrates how to raise a custom trigger error when a specific condition is detected.

24. MySQL Trigger Interview Questions and Answers

Q1. What is a trigger in MySQL?

A trigger is a database object associated with a table that automatically executes when a specified table event occurs.

Q2. What is a BEFORE INSERT trigger?

It executes before a row is inserted and can validate or modify incoming values.

Q3. What is an AFTER INSERT trigger?

It executes after the row operation succeeds and can perform related operations such as audit logging.

Q4. What is the difference between BEFORE INSERT and AFTER INSERT?

BEFORE INSERT can prepare incoming values before storage. AFTER INSERT responds to a completed insertion and cannot modify that inserted row through NEW assignments.

Q5. What does NEW mean in an INSERT trigger?

NEW refers to the column values of the row being inserted.

Q6. Can a BEFORE INSERT trigger modify an incoming value?

Yes. Where permitted, it can use a statement such as SET NEW.product_name = UPPER(NEW.product_name);.

Q7. Can an AFTER INSERT trigger change the inserted row using SET NEW?

No. The row has already been inserted. Transform the incoming value in a BEFORE INSERT trigger instead.

Q8. What is FOR EACH ROW?

It specifies that the trigger body executes for each row affected by the triggering operation.

Q9. Why is DELIMITER used when creating a trigger?

In the MySQL command-line client, it temporarily changes the statement terminator so semicolons inside a compound trigger body do not terminate the CREATE TRIGGER statement prematurely.

Q10. What is SIGNAL SQLSTATE '45000' used for?

It raises a user-defined exception and can provide a custom error message when a validation condition fails.

Q11. Can a table have more than one BEFORE INSERT trigger?

Yes. MySQL permits multiple triggers with the same table, event, and timing. Their order can be controlled using FOLLOWS or PRECEDES when appropriate.

Q12. What happens if an AFTER INSERT trigger fails?

The statement that activated the trigger fails. With transactional tables, changes made by the failed statement are rolled back.

Q13. How can you display existing triggers?

Use SHOW TRIGGERS; in the selected database.

Q14. How do you remove a trigger?

Use DROP TRIGGER IF EXISTS trigger_name;.

Q15. Why are AFTER INSERT triggers useful for audit logging?

They can record information about a row after the insertion succeeds, helping maintain a history of successfully inserted records.

25. Quick Revision Notes

  • Trigger: A stored database object that executes automatically in response to a specified table event.
  • BEFORE INSERT: Runs before a row is inserted.
  • AFTER INSERT: Runs after the row insertion succeeds.
  • NEW: Provides access to incoming column values in INSERT triggers.
  • SET NEW.column_name: Changes an incoming value in a BEFORE trigger where permitted.
  • FOR EACH ROW: Specifies row-level trigger execution.
  • BEGIN...END: Groups multiple statements into a compound trigger body.
  • DELIMITER: Temporarily changes the statement terminator in clients that require it for compound definitions.
  • SIGNAL: Raises an error when a validation rule is violated.
  • SHOW TRIGGERS: Displays triggers for the selected database.
  • SHOW CREATE TRIGGER: Displays a trigger's definition.
  • DROP TRIGGER: Removes a trigger.

26. Conclusion

BEFORE INSERT and AFTER INSERT triggers are important MySQL features for automating database operations. A BEFORE INSERT trigger is useful for validating, standardizing, or modifying incoming data before it is stored. An AFTER INSERT trigger is useful for recording successful insertions and performing permitted follow-up database operations.

By practicing trigger creation, NEW column references, validation with SIGNAL, audit logging, and trigger management, you can build more consistent and maintainable database workflows. Keep trigger logic focused, use constraints for simple data rules, and test how errors affect related operations.

Continue Learning: Visit the MySQL Training Course to explore additional database topics, and use the Course Demo Registration page to learn more about the training.

whatsapp